package com.sumainfor.pc.epc.service.impl;

import com.google.common.collect.Lists;
import com.sumainfor.common.entity.SearchEntity;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.HtmlUtil;
import com.sumainfor.pc.epc.dao.SearchMapper;
import com.sumainfor.pc.epc.feign.GetUserInfoFeign;
import com.sumainfor.pc.epc.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.pc.epc.feign.Zfeign.ZwxTenantFeign;
import com.sumainfor.pc.epc.feign.Zfeign.ZzuulFeign;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author EddyChen
 * @Email 835033913@qq.com
 * @Create 2019/6/25 19:07
 * 工程部的搜索
 */
@Service
public class SearchService {

    @Autowired
    private SearchMapper mapper;

    @Autowired
    private ZpcMktFeign mktFeign;

    @Autowired
    private GetUserInfoFeign getUserInfoFeign;

    @Autowired
    private ZzuulFeign zullFeign;

    @Autowired
    private ZwxTenantFeign tenantFeign;

    /**
     * 搜索  - 维修师傅
     *
     * @param search
     * @return
     */
    public JsonResult searchForWs(String search) {
        JsonResult<List<String>> jsonResult = mktFeign.selectProjectIdList(search);
        if (!jsonResult.isSuccess()) {
            return jsonResult;
        }
        List<String> comIds = jsonResult.getResult();

        List<SearchEntity> dataList = Lists.newArrayList();

        //搜索我的工单
        List<Map<String, Object>> myRepair = mapper.selectMyRepair(comIds, ContextUtils.getUserId());
        SearchEntity mySearch = new SearchEntity();
        mySearch.setName(String.format("我的工单(%d)", myRepair.size()));
        mySearch.setRouter("/sys-engineeringassistant/repairmanage");
        mySearch.setList(myRepair.stream().map(myItem -> {
            StringBuffer myItemStr = new StringBuffer(HtmlUtil.BR);
            DateUtils.formatDateByMap(myItem);
            myItemStr.append(MapUtils.getString(myItem, "RepId"))
                    .append(HtmlUtil.BR)
                    .append(MapUtils.getInteger(myItem, "OrdType").equals(1) ? "普通工单" : "维修房")
                    .append(HtmlUtil.BR)
                    .append("联系电话:").append(MapUtils.getString(myItem, "Phone"))
                    .append(HtmlUtil.BR)
                    .append(MapUtils.getInteger(myItem, "RepArea").equals(1) ? "公共区域" : "个人区域")
                    .append(HtmlUtil.BR)
                    .append(MapUtils.getInteger(myItem, "OrdState").equals(2) ? "已维修" : "待维修")
                    .append(HtmlUtil.BR)
                    .append("完成时间:").append(MapUtils.getString(myItem, "FinishTime", "-"));

            return HtmlUtil.stringToHTML(myItemStr.toString(), MapUtils.getString(myItem, "RepId"), Color.red);

        }).collect(Collectors.toList()));
        dataList.add(mySearch);

        //搜索维修工单池
        List<Map<String, Object>> repair = mapper.selectRepair(comIds);
        SearchEntity repairSearch = new SearchEntity();
        repairSearch.setName(String.format("维修工单池(%d)", repair.size()));
        repairSearch.setRouter("/sys-engineeringassistant/repairmanage");
        repairSearch.setList(repair.stream().map(rItem -> {
            StringBuffer myItemStr = new StringBuffer(HtmlUtil.BR);
            DateUtils.formatDateByMap(rItem);
            myItemStr.append(MapUtils.getString(rItem, "RepId"))
                    .append(HtmlUtil.BR)
                    .append(MapUtils.getInteger(rItem, "OrdType").equals(1) ? "普通工单" : "维修房")
                    .append(HtmlUtil.BR)
                    .append("联系电话:").append(MapUtils.getString(rItem, "Phone"))
                    .append(HtmlUtil.BR)
                    .append(MapUtils.getInteger(rItem, "RepArea").equals(1) ? "公共区域" : "个人区域")
                    .append(HtmlUtil.BR);
            if (MapUtils.getInteger(rItem, "RepState").equals(1)) {
                myItemStr.append("待接单");
            } else if (MapUtils.getInteger(rItem, "RepState").equals(2)) {
                myItemStr.append("已接单");
            } else {
                myItemStr.append("被强派");
            }
            myItemStr.append(HtmlUtil.BR);
            myItemStr.append(MapUtils.getInteger(rItem, "RepState").equals(2) ? "已维修" : "待维修")
                    .append(HtmlUtil.BR)
                    .append("预约上门时间:").append(MapUtils.getString(rItem, "CallTime", "-"))
                    .append(HtmlUtil.BR)
                    .append("紧急程度:").append(MapUtils.getInteger(rItem, "Urgency").equals(0) ? "普通" : "紧急");
            return HtmlUtil.stringToHTML(myItemStr.toString(), MapUtils.getString(rItem, "RepId"), Color.red);

        }).collect(Collectors.toList()));
        dataList.add(repairSearch);
        return JsonResult.success(dataList);
    }


    /**
     * 搜索  - 工程助理
     *
     * @param search
     * @return
     */
    public JsonResult searchForGcZl(String search) {
        List<SearchEntity> dataList = Lists.newArrayList();

        //1. 根据小区名称搜索待审核房源配置
        // TODO: 2019/6/26 新功能待续

        //2.根据装修计划编号搜索装修计划
        List<Map<String, Object>> list = mapper.selectPlan(search);
        SearchEntity planEntity = new SearchEntity();
        dataList.add(planEntity);
        planEntity.setName(String.format("装修计划(%d)", list.size()));
        planEntity.setRouter("sys-engineeringassistant/decorationmanagement");
        planEntity.setList(list.stream().map(planItem -> {
            StringBuffer sb = new StringBuffer(HtmlUtil.BR);
            sb.append(MapUtils.getString(planItem, "PlanId"))
                    .append(HtmlUtil.BR);
            switch (MapUtils.getInteger(planItem, "PlanState")) {
                case 1:
                    sb.append("审核中");
                    break;
                case 2:
                    sb.append("被驳回");
                    break;
                case 3:
                    sb.append("装修中");
                    break;
                default:
                    sb.append("已完成");
            }
            sb.append(HtmlUtil.BR);
            sb.append("房源套数:").append(MapUtils.getInteger(planItem, "HouCount"))
                    .append(HtmlUtil.BR);
            //查询服务中心
            Map<String, Object> miId = zullFeign.getDeptInfoById(MapUtils.getString(planItem, "MiId"));
            if (!FieldCheckUtil.isMapFieldNotNull(miId, "name")) {
                sb.append("服务中心:").append(miId.get("name")).append(HtmlUtil.BR);
            }


            //查询负责人姓名
            JsonResult<List<Map<String, Object>>> userJson = getUserInfoFeign.getUserInfo(Arrays.asList(MapUtils.getString(planItem, "SysUserId")));
            if (userJson.isSuccess() && CollectionUtils.isNotEmpty(userJson.getResult())) {
                sb.append("负责人:").append(userJson.getResult().get(0).get("username"));
            }

            return HtmlUtil.stringToHTML(sb.toString(), MapUtils.getString(planItem, "PlanId"), Color.red);
        }).collect(Collectors.toList()));
        return JsonResult.success(dataList);
    }

    /**
     * 搜索  - 工程经理
     *
     * @param search
     * @return
     */
    public JsonResult searchForGcJl(String search) {
        List<SearchEntity> dataList = Lists.newArrayList();
        //根据名称搜索维修师傅评价
        SearchEntity wxEntity = new SearchEntity();
        dataList.add(wxEntity);
        List<String> userId = zullFeign.selectRepairPeople(search).stream().map(usr -> MapUtils.getString(usr, "userId")).collect(Collectors.toList());
        List<Map<String, Object>> wxCommitList = mapper.selectCommit(search, userId);
        wxEntity.setName(String.format("维修评价(%d)", wxCommitList.size()));
        wxEntity.setRouter("/sys-engineeringmanager/wsheetpool");
        //获取维修师傅名称
        JsonResult<List<Map<String, Object>>> sysUserJson = getUserInfoFeign.getUserInfo(wxCommitList.stream().map(uid -> MapUtils.getString(uid, "SysUserId")).collect(Collectors.toList()));
        if (!sysUserJson.isSuccess() && !wxCommitList.isEmpty()) {
            return sysUserJson;
        }
        //查询租客姓名
        JsonResult<List<Map<String, Object>>> tenJson = tenantFeign.getTenantList(CustomMap.create("tidList", wxCommitList.stream().map(tenid -> MapUtils.getString(tenid, "WxUser")).collect(Collectors.toList())));
        if (!tenJson.isSuccess() && !wxCommitList.isEmpty()) {
            return tenJson;
        }
        wxEntity.setList(wxCommitList.stream().map(commit -> {
            StringBuffer sb = new StringBuffer(HtmlUtil.BR);
            sb.append(MapUtils.getString(commit, "RepId"))
                    .append(HtmlUtil.BR);
            for (Map<String, Object> usrMap : sysUserJson.getResult()) {
                if (Objects.equals(MapUtils.getString(usrMap, "user_id"), MapUtils.getString(commit, "SysUserId"))) {
                    sb.append("维修师傅:").append(usrMap.get("username")).append(HtmlUtil.BR);
                    break;
                }
            }
            for (Map<String, Object> tenMap : tenJson.getResult()) {
                if (Objects.equals(MapUtils.getString(tenMap, "TenId"), MapUtils.getString(commit, "WxUser"))) {
                    sb.append("评价人姓名:").append(tenMap.get("TenName")).append(HtmlUtil.BR);
                    break;
                }
            }
            sb.append("评价等级:").append(MapUtils.getInteger(commit, "Star")).append(HtmlUtil.BR);
            sb.append("评价内容:").append(MapUtils.getString(commit, "EvaNotes")).append(HtmlUtil.BR);
            return HtmlUtil.stringToHTML(sb.toString(), MapUtils.getString(commit, "RepId"), Color.red);
        }).collect(Collectors.toList()));


        //根据小区名称搜索维修工单池
        JsonResult<List<String>> jsonResult = mktFeign.selectProjectIdList(search);
        if (!jsonResult.isSuccess()) {
            return jsonResult;
        }
        List<String> comIds = jsonResult.getResult();

        SearchEntity repairSearch = new SearchEntity();
        dataList.add(repairSearch);
        List<Map<String, Object>> repair = mapper.selectRepair(comIds);
        repairSearch.setName(String.format("维修工单池(%d)", repair.size()));
        repairSearch.setRouter("/sys-engineeringassistant/repairmanage");
        repairSearch.setList(repair.stream().map(rItem -> {
            StringBuffer myItemStr = new StringBuffer(HtmlUtil.BR);
            DateUtils.formatDateByMap(rItem);
            myItemStr.append(MapUtils.getString(rItem, "RepId"))
                    .append(HtmlUtil.BR)
                    .append(MapUtils.getInteger(rItem, "OrdType").equals(1) ? "普通工单" : "维修房")
                    .append(HtmlUtil.BR)
                    .append("联系电话:").append(MapUtils.getString(rItem, "Phone"))
                    .append(HtmlUtil.BR)
                    .append(MapUtils.getInteger(rItem, "RepArea").equals(1) ? "公共区域" : "个人区域")
                    .append(HtmlUtil.BR);
            if (MapUtils.getInteger(rItem, "RepState").equals(1)) {
                myItemStr.append("待接单");
            } else if (MapUtils.getInteger(rItem, "RepState").equals(2)) {
                myItemStr.append("已接单");
            } else {
                myItemStr.append("被强派");
            }
            myItemStr.append(HtmlUtil.BR);
            myItemStr.append(MapUtils.getInteger(rItem, "RepState").equals(2) ? "已维修" : "待维修")
                    .append(HtmlUtil.BR)
                    .append("预约上门时间:").append(MapUtils.getString(rItem, "CallTime", "-"))
                    .append(HtmlUtil.BR)
                    .append("紧急程度:").append(MapUtils.getInteger(rItem, "Urgency").equals(0) ? "普通" : "紧急");
            return HtmlUtil.stringToHTML(myItemStr.toString(), MapUtils.getString(rItem, "RepId"), Color.red);

        }).collect(Collectors.toList()));


        //根据装修计划编号搜索装修计划
        List<Map<String, Object>> list = mapper.selectPlan(search);
        SearchEntity planEntity = new SearchEntity();
        dataList.add(planEntity);
        planEntity.setName(String.format("装修计划(%d)", list.size()));
        planEntity.setRouter("sys-engineeringassistant/decorationmanagement");
        planEntity.setList(list.stream().map(planItem -> {
            StringBuffer sb = new StringBuffer(HtmlUtil.BR);
            sb.append(MapUtils.getString(planItem, "PlanId"))
                    .append(HtmlUtil.BR);
            switch (MapUtils.getInteger(planItem, "PlanState")) {
                case 1:
                    sb.append("审核中");
                    break;
                case 2:
                    sb.append("被驳回");
                    break;
                case 3:
                    sb.append("装修中");
                    break;
                default:
                    sb.append("已完成");
            }
            sb.append(HtmlUtil.BR);
            sb.append("房源套数:").append(MapUtils.getInteger(planItem, "HouCount"))
                    .append(HtmlUtil.BR);
            //查询服务中心
            Map<String, Object> miId = zullFeign.getDeptInfoById(MapUtils.getString(planItem, "MiId"));
            if (!FieldCheckUtil.isMapFieldNotNull(miId, "name")) {
                sb.append("服务中心:").append(miId.get("name")).append(HtmlUtil.BR);
            }


            //查询负责人姓名
            JsonResult<List<Map<String, Object>>> userJson = getUserInfoFeign.getUserInfo(Arrays.asList(MapUtils.getString(planItem, "SysUserId")));
            if (userJson.isSuccess() && CollectionUtils.isNotEmpty(userJson.getResult())) {
                sb.append("负责人:").append(userJson.getResult().get(0).get("username"));
            }

            return HtmlUtil.stringToHTML(sb.toString(), MapUtils.getString(planItem, "PlanId"), Color.red);
        }).collect(Collectors.toList()));


        //根据名称搜索供应商
        List<Map<String, Object>> supplier = mapper.selectSupplier(search);
        SearchEntity supplierEntity = new SearchEntity();
        dataList.add(supplierEntity);
        supplierEntity.setName(String.format("供应商(%d)", supplier.size()));
        supplierEntity.setRouter("/sys-buyerrole/suppliermanage");
        supplierEntity.setList(supplier.stream().map(sup -> {
            StringBuffer sb = new StringBuffer(HtmlUtil.BR);
            sb.append(MapUtils.getString(sup, "SupId")).append(HtmlUtil.BR);
            sb.append(MapUtils.getString(sup, "UnitName")).append(HtmlUtil.BR);
            switch (MapUtils.getInteger(sup, "SupType")) {
                case 1:
                    sb.append("硬装供应商").append(HtmlUtil.BR);
                    break;
                case 2:
                    sb.append("软装供应商").append(HtmlUtil.BR);
                    break;
                default:
                    sb.append("保洁供应商").append(HtmlUtil.BR);
            }
            sb.append("联系人:").append(MapUtils.getString(sup, "Contact"));
            return HtmlUtil.stringToHTML(sb.toString(), MapUtils.getString(sup, "SupId"), Color.red);
        }).collect(Collectors.toList()));

        return JsonResult.success(dataList);
    }


    /**
     * 搜索  - 采购专员
     *
     * @param search
     * @return
     */
    public JsonResult searchForCg(String search) {
        List<SearchEntity> dataList = Lists.newArrayList();

        //根据发起人名称搜索采购订单
        JsonResult<List<Map<String, Object>>> userJson = zullFeign.searchUserForName(search);
        if (!userJson.isSuccess()) {
            return userJson;
        }
        List<String> userIds = userJson.getResult().stream().map(u -> MapUtils.getString(u, "userId")).collect(Collectors.toList());
        SearchEntity buyerEntity = new SearchEntity();
        dataList.add(buyerEntity);
        List<Map<String, Object>> buyerList = mapper.selectBuyerOrder(userIds);
        buyerEntity.setName(String.format("采购订单(%d)", buyerList.size()));
        buyerEntity.setRouter("/sys-engineeringmanager/buyer");

        //获取维修师傅名称
        JsonResult<List<Map<String, Object>>> sysUserJson = getUserInfoFeign.getUserInfo(buyerList.stream().map(uid -> MapUtils.getString(uid, "SysUserId")).collect(Collectors.toList()));
        if (!sysUserJson.isSuccess() && !buyerList.isEmpty()) {
            return sysUserJson;
        }

        buyerEntity.setList(buyerList.stream().map(buyer -> {
            StringBuffer sb = new StringBuffer(HtmlUtil.BR);
            sb.append(MapUtils.getString(buyer, "BuyId")).append(HtmlUtil.BR);
            sb.append(MapUtils.getString(buyer, "BuyType").equals(1) ? "装修采购单" : "备件采购").append(HtmlUtil.BR);
            if (StringUtils.isNotBlank(MapUtils.getString(buyer, "SourceId"))) {
                sb.append("装修计划编号:").append(MapUtils.getString(buyer, "SourceId")).append(HtmlUtil.BR);
            }
            switch (MapUtils.getInteger(buyer, "BuyState")) {
                case 1:
                    sb.append("待采购").append(HtmlUtil.BR);
                    break;
                case 2:
                    sb.append("采购中").append(HtmlUtil.BR);
                    break;
                case 3:
                    sb.append("已采购").append(HtmlUtil.BR);
                    break;
                case 4:
                    sb.append("审核中").append(HtmlUtil.BR);
                    break;
                default:
                    sb.append("被驳回").append(HtmlUtil.BR);

            }
            for (Map<String, Object> usrMap : sysUserJson.getResult()) {
                if (Objects.equals(MapUtils.getString(usrMap, "user_id"), MapUtils.getString(buyer, "SysUserId"))) {
                    sb.append("发起人:").append(usrMap.get("username"));
                    break;
                }
            }
            return HtmlUtil.stringToHTML(sb.toString(), MapUtils.getString(buyer, "BuyId"), Color.red);
        }).collect(Collectors.toList()));

        //根据名称搜索供应商
        List<Map<String, Object>> supplier = mapper.selectSupplier(search);
        SearchEntity supplierEntity = new SearchEntity();
        dataList.add(supplierEntity);
        supplierEntity.setName(String.format("供应商(%d)", supplier.size()));
        supplierEntity.setRouter("/sys-buyerrole/suppliermanage");
        supplierEntity.setList(supplier.stream().map(sup -> {
            StringBuffer sb = new StringBuffer(HtmlUtil.BR);
            sb.append(MapUtils.getString(sup, "SupId")).append(HtmlUtil.BR);
            sb.append(MapUtils.getString(sup, "UnitName")).append(HtmlUtil.BR);
            switch (MapUtils.getInteger(sup, "SupType")) {
                case 1:
                    sb.append("硬装供应商").append(HtmlUtil.BR);
                    break;
                case 2:
                    sb.append("软装供应商").append(HtmlUtil.BR);
                    break;
                default:
                    sb.append("保洁供应商").append(HtmlUtil.BR);
            }
            sb.append("联系人:").append(MapUtils.getString(sup, "Contact"));
            return HtmlUtil.stringToHTML(sb.toString(), MapUtils.getString(sup, "SupId"), Color.red);
        }).collect(Collectors.toList()));

        //根据名称搜索供应商结算单
        List<Map<String, Object>> statementList = mapper.selectStatementForSupplier(search);
        SearchEntity statementEntity = new SearchEntity();
        statementEntity.setName(String.format("供应商结算单(%d)", statementList.size()));
        statementEntity.setRouter("/sys-engineeringmanager/settlement");
        dataList.add(statementEntity);
        statementEntity.setList(statementList.stream().map(sta -> {
            StringBuffer sb = new StringBuffer(HtmlUtil.BR);
            sb.append("结算单编号:").append(MapUtils.getString(sta, "StaId")).append(HtmlUtil.BR);
            sb.append("供应商编号:").append(MapUtils.getString(sta, "SupId")).append(HtmlUtil.BR);
            sb.append(MapUtils.getString(sta, "UnitName")).append(HtmlUtil.BR);
            sb.append("应付金额:").append(MapUtils.getString(sta, "CopeWithPrice")).append(HtmlUtil.BR);
            sb.append("已付金额:").append(MapUtils.getString(sta, "PaidPrice")).append(HtmlUtil.BR);
            sb.append("待付金额:").append(MapUtils.getString(sta, "UnpaidPrice")).append(HtmlUtil.BR);
            sb.append("预算金额(只针对硬装供应商):").append(MapUtils.getString(sta, "BudgetPrice")).append(HtmlUtil.BR);
            sb.append("账单状态:").append(MapUtils.getInteger(sta, "State").equals(0) ? "未结清" : "已结清").append(HtmlUtil.BR);
            return HtmlUtil.stringToHTML(sb.toString(), MapUtils.getString(sta, "StaId"), Color.red);
        }).collect(Collectors.toList()));

        //根据名称搜索物品库存
        List<Map<String, Object>> shopList = mapper.selectShop(search);
        SearchEntity shopEntity = new SearchEntity();
        shopEntity.setName(String.format("商品(%d)", shopList.size()));
        shopEntity.setRouter("/sys-buyerrole/thingmanage");
        dataList.add(shopEntity);
        shopEntity.setList(shopList.stream().map(shop -> {
            StringBuilder sb = new StringBuilder(HtmlUtil.BR);
            sb.append("商品名称:").append(MapUtils.getString(shop, "ComName")).append(HtmlUtil.BR);
            sb.append("商品品牌:").append(MapUtils.getString(shop, "ComBrand")).append(HtmlUtil.BR);
            sb.append("规格名称:").append(MapUtils.getString(shop, "ComSpeName")).append(HtmlUtil.BR);
            sb.append("型号名称:").append(MapUtils.getString(shop, "ComSpeMoName")).append(HtmlUtil.BR);
            sb.append("实际总库存:").append(MapUtils.getString(shop, "Stock")).append(HtmlUtil.BR);
            return HtmlUtil.stringToHTML(sb.toString(), MapUtils.getString(shop, "ComName"), Color.red);
        }).collect(Collectors.toList()));

        return JsonResult.success(dataList);
    }
}
